/**
 *       Copyright (c) 2011 Lukas Zaruba
 * 
 *   This file is part of ParPortTester
 *
 *   ParPortTester is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   ParPortTester is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with ParPortTester. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.parporttester.dynNOResp;

import net.zarubsys.parporttester.utils.IOHWUtils;

import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

/**
 * @author  &lt;A HREF=&quot;mailto:lukas.zaruba@gmail.com&quot;&gt;Lukas Zaruba&lt;/A&gt; zarubsys.net
 */
public class OHWPage extends WizardPage {
	
	public OHWPage() {
		super("HW"); //$NON-NLS-1$
		setTitle(Messages.OHWPage_title);
		setDescription(Messages.OHWPage_description);
	}
	
	private Combo addressCombo;
	private Combo outputOffset;
	private Text outputMask;

	@Override
	public void createControl(Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayout(new GridLayout(2, false));
		createControlInternal(composite);
		setControl(composite);
		validate();
	}
	
	protected void createControlInternal(Composite composite) {
		Label label;
		label = new Label(composite, SWT.NONE);
        label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
        label.setText(Messages.OHWPage_labels_port);
		addressCombo = new Combo(composite, SWT.NONE);
		addressCombo.setItems(getAddressItems());
		addressCombo.select(0);
		
		label = new Label(composite, SWT.NONE);
        label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
        label.setText(Messages.OHWPage_labels_outputOffset);
		outputOffset = createOffsetCombo(composite);
		outputOffset.select(0);
		
		label = new Label(composite, SWT.NONE);
        label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
        label.setText(Messages.OHWPage_labels_outputMask);
		outputMask = createMaskText(composite, "00000100"); //$NON-NLS-1$
	}
	
	private String[] getAddressItems() {
		return IOHWUtils.getInstance().getPortNames();
	}
	
	protected Combo createOffsetCombo(Composite parent) {
		Combo combo = new Combo(parent, SWT.NONE);
		combo.setItems(new String[] {"Data", "Status (+1)", "Control (+2)"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		return combo;
	}
	
	protected boolean validate() {
		if (!validateOffset(outputMask.getText(), Messages.OHWPage_labels_output)) return false;
		return true;
	}
	
	private void setUserOutput(String text) {
        if (text != null) {
                setErrorMessage(text);
                setPageComplete(false);
        } else {
                setErrorMessage(null);
                setPageComplete(true);
        }
	}
	
	protected Text createMaskText(Composite parent, String defaultValue) {
		Text mask = new Text(parent, SWT.SINGLE | SWT.BORDER);
		mask.setText(defaultValue);
		mask.setTextLimit(8);
		mask.addModifyListener(new ModifyListener() {
			
			@Override
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});
		
		return mask;
	}
	
	protected boolean validateOffset(String text, String namePrefix) {
		String errorMessage = namePrefix + Messages.OHWPage_errors_illegalOffset;
		if (text == null || text.length() != 8) {
			setUserOutput(errorMessage);
			return false;
		}
		
		boolean found1 = false;
		for (char c : text.toCharArray()) {
			if (c != '0' && c != '1') {
				setUserOutput(errorMessage);
				return false;
			}
			
			if (c == '1') {
				if (found1) {
					setUserOutput(errorMessage);
					return false;
				}
				found1 = true;
			}
		}
		
		try {
			Integer.parseInt(text, 2);
		} catch (Exception e) {
			setUserOutput(errorMessage);
			return false;
		}
		
		setUserOutput(null); // clear errors
		return true;
	}
	
	public OHWPageResult getResultData() {
		int baseAddress = IOHWUtils.getInstance().getPortAddress(addressCombo.getSelectionIndex());
		int outputAddress = IOHWUtils.getInstance().addOffset(baseAddress, outputOffset.getSelectionIndex());
		int outputMaskValue = Integer.parseInt(outputMask.getText(), 2);
		return new OHWPageResult(baseAddress, outputAddress, outputMaskValue);
	}

}
